#!/usr/bin/python3
import os
from .Entity import Entity
from utils import My_Util2


class Cachekey:
    """
    缓存键枚举
    """

    def __init__(self, context, entities: list[Entity]) -> None:
        self.context = context
        self.entities: list[Entity] = sorted(entities, key=lambda item: item.table_name)
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_includes(self):
        framework_package = f"""{self.context['package']}.{self.context['framework_package']}"""
        includes = list()
        includes.append(f"""import {framework_package}.support.assertion.SystemAssert;""")
        includes.append(f"""import {framework_package}.support.constants.StringConstants;""")
        includes.append(f"""import {framework_package}.support.context.TenantContext;""")
        includes = self.my_util2.sort_import_order(includes)
        return "\r".join(includes)

    def code_cache_key(self):
        entities = list[str]()
        for entity in self.entities:
            prefix = entity.table_name.split("_")[0]
            entities.append(
                f"""
    /**
     * {entity.comment}分布式锁
     */
    LOCK_{entity.table_name}("{prefix}:LOCK:{entity.table_name}"),

    /**
     * {entity.comment}缓存
     */
    {entity.table_name}("{prefix}:VAL:{entity.table_name}"),"""
            )
        return "\n".join(entities)

    def code(self):
        _id = self.context['id']
        author = self.entities[0].author if len(self.entities) > 0 else ""
        package = self.entities[0].package if len(self.entities) > 0 else ""
        includes = self.code_includes()
        cachekeys = self.code_cache_key()
        return f"""package {package}.{self.context["code_storage"]["root"]}.constants;

{includes}

/**
 * 缓存键枚举
 *
 * @author {author}
 */
public enum CacheKeyEnum {"{"}
{cachekeys}
    ;

    private final String value;

    /**
     * 统一前缀
     */
    private final static String PREFIX = "{_id}";

    CacheKeyEnum(String value) {"{"}
        this.value = value;
    {"}"}

    /**
     * 组装并获取缓存键 .
     *
     * @param key 缓存键
     * @return java.lang.String 组装后的缓存键
     * @author {author}
     */
    public String key(String key) {"{"}
        SystemAssert.hasLength(key, "缓存键不能为空");
        return String.join(StringConstants.Symbol.COLON, PREFIX, this.value, TenantContext.getIsTenant() ? String.valueOf(TenantContext.getTenantId()) : StringConstants.EMPTY, key);
    {"}"}
{"}"}
"""

    def save_file(self, dir):
        _target_dir = os.path.join(dir, self.context["code_storage"]["root"], "constants")
        if not os.path.exists(_target_dir):
            os.makedirs(_target_dir)
        with open(
            os.path.join(_target_dir, "CacheKeyEnum.java"),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())
